

<template>
    <div class="Main">
        <div class="MainTitle">
            角色管理
        </div>
        <div class="MianContent">
            <div class="MainTopAction">
                <div class="flex align-center">
                    <a-button style="margin-right:10px;" icon="plus" type="primary" @click="AddMenu">新增角色</a-button>
                </div>
                <div class="flex align-center">
                    <a-input v-model="keyword" allowClear @change="InputChange" style="width: 300px;" placeholder="请输入信息查询" />
                    <a-button class="ml-10" type="primary" @click="SeachKeyword">搜索</a-button>
                </div>
            </div>
            <div class="TableView">
                <a-table :columns="listfields" :data-source="listData" bordered size="middle" :pagination="false">
                    <div slot="action" slot-scope="row, index">
                        <a-button v-if="index.parentId == 0" style="margin:0 10px 0 0;" type="info" size="small" @click="AddChildNode(index)">添加子角色</a-button>
                        <a-button style="margin:0 10px 0 0;" type="primary" size="small" @click="DistriRoot(index)">分配权限</a-button>
                        <a-button style="margin:0 10px 0 0;" type="primary" size="small" @click="EditNode(index)">详情</a-button>
                        <a-popconfirm placement="bottom" ok-text="删除" cancel-text="取消" @confirm="DeleteItem(index)">
                            <template slot="title">
                                <p>警告</p>
                                <p>此操作将删除该商品, 是否继续?</p>
                            </template>
                            <a-button type="danger" size="small">删除</a-button>
                        </a-popconfirm>
                    </div>
                    <div slot="icon" slot-scope="row,index">
                      <!-- <a-icon :type="row" /> -->
                      {{row}}
                    </div>
                    <div slot="isMenu" slot-scope="row,index">
                      <!-- <a-icon :type="row" /> -->
                      {{row==0?'是':'否'}}
                    </div>
                </a-table>
                <Pagination :total="total" v-model="pageno" :pageSize.sync="pagesize" @change="handlePageChange" @onShowSizeChange="onShowSizeChange"></Pagination>
            </div>
        </div>
        <a-modal :title="ModalTitle" v-model="visible" :width="800" :centered="true" :maskClosable="false" @ok="handleOk" @cancel="handleCancel">
            <div style="padding-left: 10px;">
                <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                    <a-form-model-item label="角色名称" prop="authorityName">
                        <a-input v-model="form.authorityName" placeholder="请输入角色名称" allowClear />
                    </a-form-model-item>
                    <a-form-model-item v-if="ModalTitle == '新增角色' || ModalTitle == '新增子角色'" label="角色ID" prop="authorityId">
                        <a-input v-model="form.authorityId" placeholder="请输入角色ID" allowClear />
                    </a-form-model-item>
                    <a-form-model-item label="默认菜单">
                        <a-input v-model="form.defaultRouter" placeholder="请输入默认菜单" allowClear />
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>

        <!-- 分配权限对话框 -->
        <a-modal :title="ModalRootTitle" v-model="visibleRoot" :width="800" :centered="true" :maskClosable="false" @ok="handleRootOk" @cancel="handleCancelRoot">
            <div style="padding-left: 10px;">
                <!-- <a-tree
                  v-model="checkedKeys"
                  checkable
                  :expanded-keys="expandedKeys"
                  :auto-expand-parent="autoExpandParent"
                  :selected-keys="selectedKeys"
                  :tree-data="treeData"
                  :replace-fields="replaceFields"
                  @expand="onExpand"
                  @select="onSelect"
                  @check="onCheck"
                /> -->
                 <a-collapse v-model="activeKey" @change="changeColl">
                  <a-collapse-panel :showArrow="item.hasChild" :disabled="!item.hasChild" :key="`${index}`" :header="item.meta.title" v-for="(item,index) in treeData">
                    <div class="flex align-center justify-between pl-40 py-5" v-for="(items,indexs) in item.children" :key="indexs">{{items.meta.title}}<a-checkbox :checked="items.checked" @change="selectChildMenu(index,indexs,items)"></a-checkbox></div>
                    <a-checkbox slot="extra" @change.stop="selectFatherMenu(index,item)" :checked="item.checked"></a-checkbox>
                  </a-collapse-panel>
                </a-collapse>
            </div>
        </a-modal>
    </div>
</template>

<script>
    import { mapGetters, mapState, mapActions } from 'vuex';
    import { showErrors, showError, showSuccess } from '@/utils/showMsg';
    import Pagination from '@/components/common/pagination.vue'
    import { RoleList } from '@/views/Columns/Root'
    import { GetAuthorityList, CreateAuthority, UpdateAuthority, DeleteAuthority, GetBaseMenuTree, GetMenuAuthority, AddMenuAuthority } from '@/api/api.js';
    import env from '@/config/env';
    import request from '@/utils/request';
import menu from '../../components/Menu/menu';

    export default {
        name: 'list',
        components: {
            Pagination,
        },
        data() {
            return {
                total: 0, //定义初始有多少条数据
                pageno: 1, //默认第几页
                pagesize: 10, //一页显示多少条数据
                keyword: '',
                OrderStatus: '',
                listfields: RoleList, //表头列表
                listData: [], //表格数据
                cate:undefined, //进食阶段
                allergy:undefined, //辅食类型

                labelCol: { span: 4 },
                wrapperCol: { span: 20 },
                visible:false,
                ModalTitle:'新增角色',
                form:{
                  authorityName:'', //角色名称
                  defaultRouter:'', //默认菜单
                  parentId:0, //父id
                  authorityId:'', //角色ID
                },

                rules:{
                  authorityName: [
                    { required: true, message: "请输入角色名称!", trigger: "blur" },
                  ],
                  authorityId: [
                    { required: true, message: "请输入大于0的正整数角色ID!", trigger: "blur", pattern: new RegExp(/^[1-9]\d*$/),},
                  ],
                },


                ModalRootTitle:'分配权限',
                visibleRoot:false,
                treeData:[], //权限菜单数据
                expandedKeys: [],
                autoExpandParent: true,
                checkedKeys: [],
                selectedKeys: [],
                replaceFields:{
                  key:'ID',
                },
                authorityId:'',//分配权限时使用的角色ID
                activeKey:[]
            };
        },
        computed: {
            ...mapState({}),
        },
        created() {},
        mounted() {
            let that = this;
            that.GetList()
        },
        methods: {
            ...mapActions({}),

            // 
            changeColl(key){
              console.log(key);
            },

            // 选中父菜单
            selectFatherMenu(index,item){
              const that = this;
              if(item.children && item.children.length){
                if(item.children.findIndex(item=>item.checked == true) != -1){
                  // 有子菜单选中
                  showError('有子菜单选中，不可取消父菜单！')
                  that.treeData[index].checked = true
                }else{
                  that.treeData[index].checked = !item.checked
                }
              }else{
                that.treeData[index].checked = !item.checked
              }
            },

            // 选中子菜单
            selectChildMenu(index,indexs,items){
              const that = this;
              if(items.checked){ //初始为选中状态
                that.treeData[index].children[indexs].checked = !items.checked
              }else{
                that.treeData[index].checked = true;
                that.treeData[index].children[indexs].checked = !items.checked
              }
            },
            
            // 分配权限按钮
            DistriRoot(row){
              const that = this;
              that.authorityId = row.authorityId;
              that.visibleRoot = true;
              that.GetBaseMenuTree()
            },
            // 分配权限弹出确定
            async handleRootOk(){
              const that = this;
              // if(!that.checkedKeys.length){
              //   showError('请勾选需要的权限路由！')
              //   return
              // }
              let menusArr = []
              let handleTree = JSON.parse(JSON.stringify(that.treeData))
              console.log(that.treeData);
              console.log(handleTree);
              handleTree.forEach(item=>{
                console.log(item);
                if(item.checked){ //父菜单选中
                    if(item.children && item.children.length){ //还有子菜单
                        // for(let i = 0;i<item.children.length;i++){
                        //   // 没选中的删掉
                        //   if(!item.children[i].checked){
                        //     item.children.splice(i,1)
                        //   }
                        // }
                        item.children.forEach(items=>{
                          if(items.checked){
                            menusArr.push(items)
                          }
                        })
                    }
                    menusArr.push(item)
                }
                // else{ // 父菜单未选中

                //     if(item.children && item.children.length){ //还有子菜单
                //         for(let j = 0;j<item.children.length;j++){
                //           // 没选中的删掉
                //           if(!item.children[j].checked){
                //             item.children.splice(j,1)
                //           }
                //         }
                //     }
                //     // 删完之后还是否有子菜单
                //     if(item.children && item.children.length){
                //       menusArr.push(item)
                //     }
                // }

              })
              console.log(menusArr);
              let params = {
                authorityId:that.authorityId,
                menus:menusArr
              }
              let res = await AddMenuAuthority(params)
              if(res.data.code == 0){
                showSuccess('分配成功！')
                that.visibleRoot = false;
                that.handleCancelRoot()
              }else{
                showError(res.data.msg)
              }

            },
            // 分配权限弹出取消
            handleCancelRoot(){
              const that = this;
              that.treeData = [];
              that.activeKey = []
            },
            // 展开收起节点时触发
            onExpand(expandedKeys) {
              console.log('onExpand', expandedKeys);
              this.expandedKeys = expandedKeys;
              this.autoExpandParent = false;
            },
            onCheck(checkedKeys) {
              console.log('onCheck', checkedKeys);
              this.checkedKeys = checkedKeys;
            },
            // 点击树节点触发
            onSelect(selectedKeys, info) {
              console.log('onSelect', info);
              this.selectedKeys = selectedKeys;
            },
          
            // 获取所有动态路由菜单
            async GetBaseMenuTree(){
              const that = this;
              let res = await GetBaseMenuTree()
              if(res.data.code == 0){
                let data = res.data.data;
                if(data.menus.length){
                  data.menus.forEach(item=>{
                    item.checked = false;
                    if(item.children && item.children.length){
                      item.children.forEach(items => {
                        items.checked = false
                        item.hasChild = true; //是否还有子菜单
                      });
                    }else{
                      item.hasChild = false
                    }
                  })
                }
                that.treeData = data.menus
                that.GetMenuAuthority()
              }else{
                showError(res.data.msg)
              }
            },
            // 获取指定角色menu
            async GetMenuAuthority(){
              const that = this;
              let params = {
                authorityId:that.authorityId
              }
              let res = await GetMenuAuthority(params)
              if(res.data.code == 0){
                let data = res.data.data;
                let rootArr = [];
                data.menus.forEach(item=>{
                  that.treeData.forEach((items,index)=>{
                    if(item.ID == items.ID){
                      items.checked = true;
                      if(items.hasChild){
                        that.activeKey.push(index.toString())
                      }
                    }
                    if(items.children && items.children.length){
                      items.children.forEach(itemss=>{
                        if(item.ID == itemss.ID){
                          itemss.checked = true
                        }
                      })
                    }
                  })
                })
                console.log(that.treeData);
              }else{
                showError(res.data.msg)
              }
            },

            InputChange(e) {
                let that = this
                if (e.target.value == '') {
                    that.GetList()
                }
            },
            SeachKeyword() {
                let that = this;
                that.GetList()
            },
            GoOrderDetail(row) {
                this.$router.push({ name: 'OrderInfo', query: { id: row.id, back: 'OrderList' } })
            },
            // 获取数据列表API
            async GetList() {
                let that = this
                let params = {
                    keyword: that.keyword,
                    page: that.pageno,
                    pageSize: that.pagesize,
                }
                const res = await GetAuthorityList(params)
                if (res.data.code == 0) {
                    // console.log(res.data);
                    const data = res.data.data
                    if (data.list.length > 0) {
                        data.list.forEach((item, index) => {
                            item.key = item.authorityId
                            item.CreatedAt = new Date(item.CreatedAt).toLocaleString(); //地区时间转换
                            if(item.children && !item.children.length){
                              item.children = null
                            }
                            if(item.children && item.children.length){
                                item.children.forEach(items => {
                                    items.key = items.authorityId
                                    items.CreatedAt = new Date(items.CreatedAt).toLocaleString(); //地区时间转换
                                    if(items.children && !items.children.length){
                                      items.children = null
                                    }
                                })
                            }
                            // item.create_time = that.$moment(item.create_time * 1000).format('YYYY-MM-DD  HH:mm:ss'); //时间戳转换成时间
                        })
                    }
                    // console.log(data);
                    that.total = data.total
                    that.listData = data.list
                } else {
                    showError(res.data.msg)
                }
            },

            // 删除节点
            async DeleteItem(row){
                const that = this;
                let res = await DeleteAuthority({authorityId:row.authorityId.toString()})
                if(res.data.code == 0){
                    showSuccess('删除成功！')
                    that.GetList()
                }else{
                    showError(res.data.msg)
                }
            },

            // 新增父节点按钮
            AddMenu(){
              const that = this;
              that.visible = true;
              that.form.parentId = 0;
              that.ModalTitle = '新增角色';
            },
            // 新增子节点按钮
            AddChildNode(row){
              const that = this;
              that.visible = true;
              that.ModalTitle = '新增子角色';
              that.form.parentId = row.authorityId;
            },

            // 编辑按钮
            EditNode(row){
                const that = this;
                that.visible = true;
                if(row.parentId == 0){
                    that.ModalTitle = '编辑角色';
                    that.form.parentId = 0;
                }else{
                    that.ModalTitle = '编辑子角色';
                    that.form.parentId = row.parentId;
                }
                that.form.authorityId = row.authorityId;
                that.form.authorityName = row.authorityName;
                that.form.defaultRouter = row.defaultRouter;
            },

            // 关闭对话框
            handleCancel(){
                const that = this;
                that.$refs.ruleForm.resetFields();
                that.form.authorityId = '';
                that.form.parentId = 0;
                that.form.authorityName = '';
                that.form.defaultRouter = '';
            },

            // 弹窗确认按钮
            handleOk(){
              const that = this;
              that.$refs["ruleForm"].validate( async (valid) => {
                if(valid){
                  let params = {
                    authorityName:that.form.authorityName,
                    defaultRouter:that.form.defaultRouter,
                    parentId:that.form.parentId.toString(),
                    authorityId:that.form.authorityId.toString()
                  }
                  let res;
                  if(that.ModalTitle == '编辑角色' || that.ModalTitle == '编辑子角色'){
                    //编辑
                    res = await UpdateAuthority(params)
                  }else{
                    // 新增
                    res = await CreateAuthority(params)
                  }
                  if(res.data.code == 0){
                    showSuccess(that.ModalTitle == '编辑角色' || that.ModalTitle == '编辑子角色'?'编辑成功！':'新增成功！')
                    that.handleCancel()
                    that.visible = false
                    that.GetList()
                  }else{
                    showError(res.data.msg)
                  }
                  
                }
              })
            },


            //分页器 
            handlePageChange(pageno, pagesize) { //点击第几页触发的函数
                let that = this;
                that.pageno = pageno;
                that.pagesize = pagesize;
                that.GetList(); //这个是向后台请求的数据函数
            },
            //切换每页显示多少条
            onShowSizeChange(current, size) { //改变每页显示条目数的函数
                let that = this;
                //pagesize 变化的回调
                that.pageno = current;
                that.pagesize = size;
                that.GetList(); //这个是向后台请求的数据函数
            },
        },
    };
</script>

<style scoped lang="less">
    .Main {
        border-radius: 10px;
        overflow: hidden;
        background: #fff;

        .MainTitle {
            font-size: 24px;
            color: #333;
            margin: 10px 20px;
            position: relative;
        }

        .MainTitle:before {
            content: '';
            width: 40px;
            height: 12px;
            background: linear-gradient(270deg, rgba(0, 158, 238, 0) 0%, rgba(221, 169, 85, 0.3) 100%);
            position: absolute;
            bottom: 2px;
            left: 0;
        }

        .MianContent {
            padding: 10px 20px 20px 20px;

            .MainTopAction {
                margin-bottom: 20px;
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                justify-content: space-between;
            }

            .TabsItem {
                padding: 10px 0;
                width: 70px;
                position: relative;
                margin-right: 24px;
                text-align: center;
                cursor: pointer;
                margin-bottom: 20px;
                color: #000;
            }

            .TabsIndex {
                color: #DDA955;
            }

            .TabsIndex::before {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translate(-50%, 0%);
                width: 50px;
                height: 2px;
                background-color: #DDA955;
            }
        }
    }
</style>